from ma.utils.clustersetup import CLUSTER_IPS, BACK_END_ACCESS_USER
import ma.utils.location as location

import os
import os.path
import time


print('WARNING: This script will first remove the ' + location.get_proj_base_path() + ' directory on all nodes before replicating the code')

# make temporary compressed tar for the code
print('Creating compressed file of the code on this node')
code_comp_filename = str(time.time()) + '.tar.gz'
os.system('tar -C ' + location.get_proj_basekeeper_path() + ' -czf ' + code_comp_filename + ' MRImprov/')

# replicate code on each node
for ip in CLUSTER_IPS:
    # delete the code directory on each node
    os.system('ssh ' + BACK_END_ACCESS_USER + '@' + ip + ' rm -rf ' + location.get_proj_base_path())
    
    # transfer the compressed file
    os.system('scp ' + code_comp_filename + ' ' + BACK_END_ACCESS_USER + '@' + ip + ':' + location.get_proj_basekeeper_path())
    
    remote_fp = os.path.join(location.get_proj_basekeeper_path(), code_comp_filename) 
    
    # extract the compressed file
    os.system('ssh ' + BACK_END_ACCESS_USER + '@' + ip + ' tar -xzf ' + remote_fp + ' -C ' + location.get_proj_basekeeper_path())
    
    # delete the compressed file
    os.system('ssh ' + BACK_END_ACCESS_USER + '@' + ip + ' rm -f ' + remote_fp)
    
    print('--- Transferred to', ip)

# delete the compressed tar file
print('Removing the temporary compressed file of the code')
os.remove(code_comp_filename)

print("Done - Khuda-Hafiz!")
